package com.sea.design.controller;


import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.data.entity.Order;
import com.sea.design.entity.Design;
import com.sea.design.service.DesignService;
import com.sea.product.service.ChannelService;

import com.sea.supply.entity.DistributeSku;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 *  设计部控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/design")
public class DesignController {
    @Autowired
    private ChannelService channelService;

    @Autowired
    private DesignService designService;

    /**
     * 运营主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        //渠道账号
        model.addAttribute("channel",channelService.findByCnd(null));
        return "/sea/operate/design/main";
    }

    /**
     * 运营主页面
     * @param model
     * @return
     */
    @RequestMapping("/designMain")
    public String designMain(Model model) {
        //渠道账号
        model.addAttribute("channel",channelService.findByCnd(null));
        return "/sea/design/designMain";
    }

    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/designEdit")
    public String designEdit(Model model, @Param("id")Integer id) {
        Design design = designService.findById(id);
        model.addAttribute("design",design);
        model.addAttribute("channel",channelService.findByCnd(null));
        return "/sea/design/designEdit";
    }

    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {
        model.addAttribute("channel",channelService.findByCnd(null));
        return "/sea/operate/design/add";
    }

    /**
     * 保存
     * @param design
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Design design) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != design && designService.save(design) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Design design) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != design && designService.usave(design) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != id && designService.delete(id) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Design design) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Design> list = designService.findByCnd(design);
        PageInfo<Design> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 导出当前数据
     * @param response
     * @param design
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, Design design)
    {
        List<Design> list = designService.findByCnd(design);
        String[] title = {
                "渠道","SKU","产品名称","商品属性","简单描述要求","设计数量","预计样品到期日","提出时间","实际完成时间","提出人","完成人","状态","备注"};
        String fileName = "分配报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "分配报表";
        String[][] content = new String[list.size()][13];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Design map = list.get(i);
            content[i][0] = map.getDesignChannelName();
            content[i][1] = map.getDesignSku();
            content[i][2] = map.getProductName();
            content[i][3] = map.getDesignProductProperty();
            content[i][4] = map.getDesignDescription();
            content[i][5] = map.getDesignNumber();
            content[i][6] = map.getDesignSampleExpiry();
            content[i][7] = map.getCreateTime();
            content[i][8] = map.getDesignComplete();
            content[i][9] = map.getDesignMember();
            content[i][10] = map.getDesignCompleteName();
            if(null==map.getDesignStatus()){
                content[i][11] = "未知";
            }else{
                switch (map.getDesignStatus()){
                    case 1:
                        content[i][11] = "未开始";
                    case 2:
                        content[i][11] = "未开始";
                    case 3:
                        content[i][11] = "已完成";
                    case 4:
                        content[i][11] = "已取消";
                }
            }


        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
